<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>

				<button class="uni-button" type="primary" size="mini" @click="uploadExcel">导入 Excel</button>

			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList"
				field="s_id,name,paper_local,video_link,video_name,quesction_list,keyword,q_sort" :where="where"
				page-data="replace" :orderby="orderby" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
				:options="options" loadtime="manual" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 's_id')"
							sortable @sort-change="sortChange($event, 's_id')">试卷ID</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'name')"
							sortable @sort-change="sortChange($event, 'name')">试卷昵称</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'paper_local')"
							sortable @sort-change="sortChange($event, 'paper_local')">定位</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'paper_local')"
							sortable @sort-change="sortChange($event, 'keyword')">关键字</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'video_link')">视频链接</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'video_name')">视频昵称</uni-th>
						<!-- 			<uni-th align="center" sortable @sort-change="sortChange($event, 'quesction_list')">题目集合
						</uni-th> -->
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.s_id}}</uni-td>
						<uni-td align="center">{{item.name}}</uni-td>
						<uni-td align="center">{{item.paper_local}}</uni-td>
						<uni-td align="center">{{item.keyword}}</uni-td>
						<uni-td align="center">
							<view v-for="(item,index) in item.video_link">
								<uni-tag :text="item" type="primary">

								</uni-tag>
							</view>


						</uni-td>
						<uni-td align="center">
							<view v-for="(item,index) in item.video_name">
								<uni-tag :text="item" type="primary">

								</uni-tag>
							</view>

						</uni-td>
						<!-- 		<uni-td align="center">
							<view v-for="(item,index) in item.quesction_list">
								<uni-tag :text="item" type="royal">

								</uni-tag>
							</view>
						</uni-td> -->
						<uni-td align="center">
							<view class="uni-group">
								<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini"
									type="primary">修改</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">删除</button>

								<button @click="befordownload(index)" class="uni-button" type="primary" size="mini">导出
									Excel

								</button>



							</view>
						</uni-td>
					</uni-tr>
				</uni-table>


				<download-excel ref="excelDownload" class="hide-on-phone" :fields="exportExcel.fields"
					:data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
				</download-excel>

				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '@/js_sdk/validator/test-paper.js';
	import * as XLSX from '@/js_sdk/xlsx/dist/xlsx.full.min.js'

	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = 'sid asc' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				cachedata: [],
				collectionList: "test-paper",
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "test-paper.xls",
					"type": "xls",
					"fields": {
						"试卷ID": "s_id",
						"试卷昵称": "name",
						"定位": "paper_local",
						"关键字": "keyword",
						"视频昵称": "video_name",
						"视频链接": "video_link",
						"题目集合": "quesction_list",
						"题目排序": "q_sort"
					}
				},
				exportExcelData: []
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
			// this.sortAll()
		},
		methods: {

			async sortAll() {
				const collection = db.collection('test-paper')
				let size = await collection.count()
				size = size.result.total
				let index = 0
				let datalist = []
				console.log('all size', size)
				while (index < size) {
					const d = await collection.field({
						_id: true,
						s_id: true
					})
					.skip(index)
					.limit(500).get()
					index += d.result.data.length
					if (d.result.data.length > 0) {
						for (let s of d.result.data) {
							s.sid = Number(s.s_id)
							datalist.push(s)
						}
					}
				}
				index = 0

				for (let s of datalist) {
					let {
						sid
					} = s
					await collection.where({
						_id: s._id
					}).update({
						sid
					})
				}


				console.log(datalist)
			},

			async befordownload(index) {
				// this.exportExcelData

				this.exportExcelData = []
				let header = {
					"s_id": this.cachedata[index]['s_id'],
					"name": this.cachedata[index]['name'],
					"paper_local": this.cachedata[index]['paper_local'],
					"keyword": this.cachedata[index]['keyword'],
					"video_name": this.cachedata[index]['video_name'][0],
					"video_link": this.cachedata[index]['video_link'][0],
					"quesction_list": this.cachedata[index]['quesction_list'][0],
					"q_sort": this.cachedata[index]['q_sort'][0]
				}
				this.exportExcelData.push(header)
				for (let i = 1; i < this.cachedata[index]['quesction_list'].length; i++) {
					this.exportExcelData.push({
						"video_link": this.cachedata[index]['video_link'][i],
						"video_name": this.cachedata[index]['video_name'][i],
						"quesction_list": this.cachedata[index]['quesction_list'][i],
						"q_sort": this.cachedata[index]['q_sort'][i]
					})
				}

				this.$nextTick(async () => {
					await this.$refs.excelDownload.generate()
				})



			},
			onqueryload(data) {
				this.cachedata = this.$cloneObject(data)
			},
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			uploadExcel() {
				const self = this
				uni.chooseFile({
					async success(res) {
						console.log(res.tempFilePaths[0])

						const url = res.tempFilePaths[0];
						const data = await (await fetch(url, {
							mode: 'no-cors'
						})).arrayBuffer();
						/* data is an ArrayBuffer */
						const workbook = XLSX.read(data);
						const xlsxData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
						let keyMap = Object.keys(self.exportExcel.fields)
						let importData = []
						let header = {
							s_id: xlsxData[0]['试卷ID'].toString(),
							sid:xlsxData[0]['试卷ID'],
							name: xlsxData[0]['试卷昵称'],
							paper_local: xlsxData[0]['定位'],
							keyword: xlsxData[0]['关键字'],
							video_link: [],
							video_name: [],
							quesction_list: [],
							q_sort: []
						}

						if (xlsxData[0]['视频链接']) {
							header.video_link.push(xlsxData[0]['视频链接'])
						}
						if (xlsxData[0]['视频昵称']) {
							header.video_name.push(xlsxData[0]['视频昵称'])
						}

						header.quesction_list.push(xlsxData[0]['题目集合'].toString())
						header.q_sort.push(xlsxData[0]['题目排序'])
						for (let i = 1; i < xlsxData.length; i++) {

							// if (xlsxData[0]['视频链接']) {
							// 	header.video_link.push(xlsxData[i]['视频链接'])
							// }
							// if (xlsxData[0]['视频昵称']) {
							// 	header.video_name.push(xlsxData[i]['视频昵称'])
							// }

							// header.video_link.push(xlsxData[i]['视频链接'])
							// header.video_name.push(xlsxData[i]['视频昵称'])
							header.quesction_list.push(xlsxData[i]['题目集合'].toString())
							header.q_sort.push(xlsxData[i]['题目排序'])
						}
						let page = 1;
						let size = 500
						let cur_size = 0;
						let resSize = header.quesction_list.length

						const q_list = []
						console.log(cur_size,resSize)
						while (cur_size < resSize) {
							let temp = await db.collection('quesction').where({
									s_id: db.command.in(header.quesction_list.slice((page-1)*size,(page-1)*size+size))
								})
								.field('s_id')
								.limit(size)
								.get()
							// console.log((page-1)*size,(page-1)*size+size)
							// console.log(header.quesction_list.slice((page-1)*size,(page-1)*size+size))
								
							for (let rows of temp.result.data) {
								q_list.push(rows)
							}
							// console.log((page-1)*size,(page-1)*size+size)
							page += 1
							cur_size += size
						
						}
						

						// console.log(q_list)
						// console.log(header.quesction_list)

						let map = new Map()
						for (let row of q_list) {
							map.set(row.s_id, true)
						}
						let notId = []
						for (let row of header.quesction_list) {
							if (!map.has(row)) {
								notId.push(row)
							}
						}
						console.log('notId',notId.length)
						if (notId.length > 0) {
							uni.showModal({
								content: "集合:" + notId.join(',') + "不存在",
								showCancel: false,
								confirmText: '复制错误信息',
								success(res) {
									if (res.confirm) {
										uni.setClipboardData({
											data: notId.join(','),
											success(info) {
												uni.showToast({
													title: '复制成功',
													duration: 1500,
													icon: 'none'
												})
											}
										})
									}
								}
							})
							return;
						}

						await db.collection('test-paper').add(header).then((res) => {
							uni.showToast({
								title: '新增成功'
							})
							self.$nextTick(() => {
								self.$refs.udb.refresh()
							})
						}).catch((err) => {
							console.log(err)
							uni.showModal({
								content: err.message,
								showCancel: false
							})
						})

					}
				})

			}
		}
	}
</script>

<style>
</style>
